//
//  mineViewController.m
//  Find
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 Reiko. All rights reserved.
//

#import "MineViewController.h"
#import "LoginViewController.h"


@interface MineViewController ()<UITableViewDataSource, UITableViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>

// 自定义tableview
@property (nonatomic, retain) UITableView * mineTableView;
// 自定义数组存储 每个cell的名字
@property (nonatomic, retain) NSArray * mineCellArray;
@property (nonatomic, retain) UIButton *loginOutButton;

@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 调用自定义界面
   [self addSubViews];
    
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self setUpData];
   
}

#pragma mark -- 自定义界面
- (void)addSubViews
{
    // 设置标题
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 60)];
    label.text = @"我的";
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont fontWithName:@"Helvetica" size:18];
    label.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = label;
    // 设置背景颜色
    self.view.backgroundColor = [UIColor whiteColor];
    // 设置导航条背景颜色 使用图片
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"iconfont-navbar-back"] forBarMetrics:UIBarMetricsDefault];
    
#pragma mark -- 自定义tableview
    self.mineTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 200 ) style:(UITableViewStylePlain)];
    self.mineTableView.delegate = self;
    self.mineTableView.dataSource = self;
    self.mineTableView.bounces = NO;
    [self.view addSubview:self.mineTableView];
    [self addTableViewHeader];

    self.mineCellArray = @[@[@"我的发布", @"我的收藏"], @[@"问题反馈"], @[@"清除缓存"],@[@"关于我们"]];
    self.loginOutButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.loginOutButton.frame = CGRectMake((kScreenWidth - 280) / 2,self.mineTableView.bottom + 10,280,40);
    [self.loginOutButton setBackgroundColor:[UIColor colorWithRed:1.000 green:0.369 blue:0.419 alpha:1.000]];
    [self.loginOutButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.loginOutButton setTitleColor:[UIColor colorWithRed:0.886 green:0.863 blue:0.854 alpha:1.000] forState:UIControlStateHighlighted];
    [self.loginOutButton setTitle:@"退出登录" forState:UIControlStateNormal];
    self.loginOutButton.layer.cornerRadius = 10;
    self.loginOutButton.layer.masksToBounds = YES;
    [self.loginOutButton addTarget:self action:@selector(actionLoginOut:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:self.loginOutButton];

}
- (void)setUpData
{
    AVUser *user = [AVUser currentUser];
    if (user) {
          self.loginOutButton.userInteractionEnabled = YES;
        // 异步调用得到缩略图
        [[user valueForKey:@"photoImage"] getThumbnail:NO width:100 height:100 withBlock:^(UIImage *image, NSError *error) {
            if (image) {
            [self.mineImage setBackgroundImage:image forState:UIControlStateNormal];
            } else {
            [self.mineImage setBackgroundImage:[UIImage imageNamed:@"placeholder.jpg"] forState:UIControlStateNormal];
            }
        }];
        [self.userNameButton setTitle:user.username forState:UIControlStateNormal];
    } else {
         self.loginOutButton.userInteractionEnabled = NO;
         [self.userNameButton setTitle:@"点击登录" forState:UIControlStateNormal];
         [self.mineImage setBackgroundImage:[UIImage imageNamed:@"placeholder.jpg"] forState:UIControlStateNormal];
    }
    
}

- (void)actionLoginOut:(UIButton *)button

{
    // 退出服务器的登录
    [AVUser logOut];
    [self setUpData];
}
#pragma  mark -- 设置总表头
- (void)addTableViewHeader
{
    UIView * headerView = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, kScreenWidth, 170))];
    headerView.backgroundColor = [UIColor whiteColor];
    // 头像
    self.mineImage = [[UIButton alloc] initWithFrame:(CGRectMake((kScreenWidth - 100) / 2, 10, 100, 100))];
       // 打开图片形变属性
  //  self.mineImage.backgroundColor = [UIColor redColor];
    self.mineImage.layer.masksToBounds = YES;
    // 将图片设置为圆形
    self.mineImage.layer.cornerRadius = self.mineImage.frame.size.height / 2;
    [self.mineImage addTarget:self action:@selector(actionMineImage:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:self.mineImage];
    // 个人昵称
    self.userNameButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.userNameButton.frame = CGRectMake((kScreenWidth - 200) / 2, self.mineImage.bottom + 10, 200, 30);
    [self.userNameButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
     [self.userNameButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    
   // self.userNameButton.backgroundColor = [UIColor redColor];
    [self.userNameButton addTarget:self action:@selector(actionUserNameButton:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:self.userNameButton];
     self.mineTableView.tableHeaderView = headerView;

}
#pragma  mark --- 头像的点击方法
- (void)actionMineImage:(UIButton *)button
{
    AVUser *user = [AVUser currentUser];
    if (user) {
     // UIImagePickerController 图片获取控制器
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        // 打开相册选择图片
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 模态进入相册
        [self presentViewController:picker animated:NO completion:nil];

    }


        
    } else {
        [self showAlterViewWithTitle:@"提示" Message:@"请先登录"];
    }
}
#pragma  mark --- 用户名按钮的点击方法
- (void)actionUserNameButton:(UIButton *)button
{
    AVUser *user = [AVUser currentUser];
    if (user) {
        return;
    } else {
        LoginViewController  *loginVC = [[LoginViewController alloc] init];
        UINavigationController *naC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [self presentViewController:naC animated:YES completion:nil];
    }

}
#pragma mark --选择相册完成后自动调用的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
   // 需要的图片
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    NSData *imageData = UIImagePNGRepresentation(image);
    AVUser *user = [AVUser currentUser];
    [self.mineImage setImage:image forState:UIControlStateNormal];
    AVFile *photoImage = [AVFile fileWithName:[NSString stringWithFormat:@"%@.png",user.username] data:imageData];
   
    [user setObject:photoImage forKey:@"photoImage"];
    [user saveInBackground];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma  mark ---  实现tableview 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.mineCellArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = self.mineCellArray[section];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"MineViewController";
    UITableViewCell * mineCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (mineCell == nil) {
        mineCell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:identifier];
        
    }
    if (indexPath.section ==  2) {
        mineCell.detailTextLabel.text = [NSString stringWithFormat:@"(%.1fM)",[self folderSizeAtPath:kCachePath]];
    }
    // 右边跳转图标
    mineCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    mineCell.textLabel.text = self.mineCellArray[indexPath.section][indexPath.row];
    
    
    UIView *selectView = [[UIView alloc] init];
    selectView.backgroundColor = [UIColor clearColor];
    mineCell.selectedBackgroundView = selectView;
    return mineCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 15;
}

// 点击跳转页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AVUser *user = [AVUser currentUser];
    switch (indexPath.section) {
            // 我的发布和收藏
        case 0:
            if (user) {
                MinePublishViewController *publishVC = [[MinePublishViewController alloc] init];
                if (indexPath.row == 0){
                    publishVC.minePublishCollec = NO;
                } else {
                    publishVC.minePublishCollec = YES;
                }
                  [self.navigationController pushViewController:publishVC animated:YES];
            } else {
                [self showAlterViewWithTitle:@"提示" Message:@"请先登录或者注册"];
            }
            break;
            // 消息中心
        case 1:
        {
            MineSettingViewController *mine = [[MineSettingViewController alloc] init];
            mine.flag = @"反馈";
            [self.navigationController pushViewController:mine animated:YES];
            break;
        }
            // 清除缓存
        case 2:{
            [SVProgressHUD showWithStatus:@"正在清除缓存..."];
            [self clearCache:kCachePath];
            UITableViewCell *cell =  [tableView cellForRowAtIndexPath:indexPath];
            float cacheSize = [self folderSizeAtPath:kCachePath];
            cell.detailTextLabel.text = [NSString stringWithFormat:@"(%.2fM)",cacheSize];
            [SVProgressHUD dismiss];
            break;
        }
            // 隐私与安全,关于我们
        case 3:
        {
            MineSettingViewController *mine = [[MineSettingViewController alloc] init];
            mine.flag = @"关于";
            [self.navigationController pushViewController:mine animated:YES];
            break;
        }
        default:
            break;
    }
}
// 封装一个alertView
- (void)showAlterViewWithTitle:(NSString *)title Message:(NSString *)message
{
    
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [self performSelector:@selector(closeAlter:) withObject:alertView afterDelay:1];
    
    [self presentViewController:alertView animated:YES completion:nil];
}
// 设置1秒之后消失
- (void)closeAlter:(UIAlertController *)alert
{
    [alert dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    
}

// 计算目录大小
- (float)folderSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    float folderSize;
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles = [fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            folderSize += [self fileSizeAtPath:absolutePath];
        }
        //SDWebImage框架自身计算缓存的实现
        folderSize += [[SDImageCache sharedImageCache] getSize] /1024.0/1024.0;
        return folderSize;
    }
    return 0;
}

// 计算单个文件
- (float)fileSizeAtPath:(NSString *)path{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size/1024.0/1024.0;
    }
    return 0;
}

// 清理缓存文件
- (void)clearCache:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            //            if ([fileName isEqualToString:@"com.Lanou.OrangeAmusement"]) {
            //                break;
            //            }
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
    [[SDImageCache sharedImageCache] cleanDisk];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
